import os
import sys
import traceback
from apscheduler.schedulers.blocking import BlockingScheduler
from Black_Screen_detection import detect_black_frames
from auto_jy import VideoProcessor
from config_logger import config, log
from diskDetection import check_c_drive_space
from extract_zip import VideoDownloader
from nofity import notify_server
from send_message import Send
from uploadOSS import OSSUploader
from apscheduler.triggers.interval import IntervalTrigger
import concurrent.futures


Drafts_path = config.get('JY_PATH', 'Drafts_path')
export_path = config.get('JY_PATH', 'export_path')

downloader = VideoDownloader(Drafts_path)
video_processor = VideoProcessor(directory=export_path, app_path=config.get('JY_PATH', 'app_path'))
user = OSSUploader()
cache_path = os.path.join(os.environ['LOCALAPPDATA'],
                                  'JianyingPro', 'User Data', 'Projects',
                                  'com.lveditor.draft')
user.clear_folder(Drafts_path)  # 清空文件
user.clear_folder(export_path)  # 清空文件
user.clear_folder(cache_path)  # 删除草稿异常缓存文件



def main():
    try:
        is_low_space = check_c_drive_space()
        if is_low_space:
            Send.qywxmsg(f"磁盘空间不足1GB")
            return
        video_processor.kill_processes_by_name("JianyingPro.exe")
        user.clear_folder(Drafts_path)  # 清空文件
        task_id, ip, video_id ,organizeId = downloader.download_and_extract_zip()  # 下载并解压
        if task_id:
            for i in range(2):
                user.clear_folder(export_path)  # 清空文件
                user.clear_folder(cache_path)  # 清空文件
                export_result = video_processor.autoJy(task_id, video_id)    # 导出

                if export_result:
                    oss_url = user.upload_file(fr"{export_path}\{video_id}.mp4", f"{organizeId}/video/jy/{video_id}.mp4")
                    if oss_url:
                        notify_server(ip, task_id, 2, oss_url)  # 发送通知
                        black_screen = detect_black_frames( fr"{export_path}\{video_id}.mp4")
                        Send.qywxmsg(f"{ip},task_id:{task_id}视频出现黑屏,帧数：{black_screen},视频:{oss_url}") if black_screen else None
                    break

                elif not export_result and i == 0:
                    video_processor.kill_processes_by_name("JianyingPro.exe")
                    continue

                elif not export_result and i == 1:
                    root_path = os.path.dirname(sys.executable) if getattr(sys, 'frozen', False) else os.path.dirname(
                        os.path.abspath(__file__))  # 打包后运行当前路径会和本地不一致
                    error_images_url = OSSUploader().upload_file(root_path + rf"\logs\{task_id}.png",
                                                               f"{organizeId}/video/jy/errorImages/{task_id}.png")
                    notify_server(ip, task_id, -2, errorInfo=error_images_url)  # 发送失败通知
                    Send.qywxmsg(f"{ip},task_id:{task_id}生成失败,失败截图：{error_images_url}")
                    break

    except BaseException as e:
        msg = traceback.format_exc()
        log.error(f"主程序未知错误：{msg}")

if __name__ == '__main__':

    interval = int(config.get('ENV', 'interval'))
    # 创建调度器
    scheduler = BlockingScheduler()

    # 创建触发器，设置间隔时间，例如每1分钟执行一次
    trigger = IntervalTrigger(seconds=interval)

    # 添加任务，设置coalesce=True，确保任务串行执行
    scheduler.add_job(main, trigger, coalesce=True)

    try:
        log.info("定时任务开始...")
        scheduler.start()  # 启动调度器
    except (KeyboardInterrupt, SystemExit):
        log.error("定时任务结束！")
